package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouritePackage;
import yxy.game.pm2.active.module.actfavoritewarlord.FavouriteTask;
import yxy.game.pm2.bean.*;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.mail.MailHandle;
import yxy.game.pm2.module.mail.MailTypeEnum;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActiveModule_心仪武将活动 extends PlayerModule {

    //bean ----------------------------------------------------

    public static final int acttype = 505;
    public static final int lotteryOnce = 1;//单抽
    public static final int lotteryTen = 2; //十连
    public static final int selecthero = 3;//选心仪武将

    private int day;            //第几天
    private DateTime update;    //刷新时间
    private int selectid;       //心仪的武将
    private int cknum;          //抽卡次数
    private ArrayList<FavouritePackage> dgifts = new ArrayList<FavouritePackage>();//心仪武将商品信息
    private HashMap<Integer, FavouriteTask> taskMap = new HashMap<Integer, FavouriteTask>();//心仪武将任务
    private Format format;      //阵容
    private int process;       //进度
    private ArrayList<String> rewardList;//已发过的奖励关卡

    public ArrayList<String> getRewardList() {
        return rewardList;
    }

    public void setRewardList(ArrayList<String> rewardList) {
        this.rewardList = rewardList;
    }

    public Format getFormat() {
        return format;
    }

    public void setFormat(Format format) {
        this.format = format;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public DateTime getUpdate() {
        return update;
    }

    public void setUpdate(DateTime update) {
        this.update = update;
    }

    public int getSelectid() {
        return selectid;
    }

    public void setSelectid(int selectid) {
        this.selectid = selectid;
    }

    public int getCknum() {
        return cknum;
    }

    public void setCknum(int cknum) {
        this.cknum = cknum;
    }

    public ArrayList<FavouritePackage> getDgifts() {
        return dgifts;
    }

    public void setDgifts(ArrayList<FavouritePackage> dgifts) {
        this.dgifts = dgifts;
    }

    public HashMap<Integer, FavouriteTask> getTaskMap() {
        return taskMap;
    }

    public void setTaskMap(HashMap<Integer, FavouriteTask> taskMap) {
        this.taskMap = taskMap;
    }

    public int getProcess() {
        return process;
    }

    public void setProcess(int process) {
        this.process = process;
    }

    //func ----------------------------------------------------

    /**
     * 创建ActiveModule_武将直升活动
     *
     * @param playerCode
     */
    public static ActiveModule_心仪武将活动 create(String playerCode) {
        AreaBean ab = AreaModule.area(playerCode);
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai != null) {
            ActiveModule_心仪武将活动 am = new ActiveModule_心仪武将活动();
            am.setPlayerCode(playerCode);
            am.setTimeline(sai.getTimeline());
            am.reset();
            am.set();
            return am;
        }
        return null;
    }

    public void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        ServerBean sb = ServerBean.get(pb.getServerId());
        activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
        if (sai == null) {
            return;
        }

        // 区活动关闭，但自己活动没关闭，更新活动时间
        if (!sai.running() ) {

            try {
                //todo 活动关闭，清除背包的没消耗完的活动道具
                actfavoritewarlord data = DataCenter.getData(1, actfavoritewarlord.class);
                int costid = data.getCostid();//消耗的道具id
                //如果背包存在就转成对应物品邮件发送
                Currency currency = Item.get(getPlayerCode(), CurrencyType.CT_物品, costid);
                if (currency.getNumber() > 0) {
                    item item_ = DataCenter.getData(costid, item.class);
                    new CurrencyHandle().cost(getPlayerCode(), CCReason.心仪武将活动抽奖道具清空, currency);
                    //邮件补偿
                    List<Currency> list = new ArrayList<>();
                    Currency reward = Currency.create(item_.getReclaimtype(), item_.getReclaimid(), currency.getNumber() * item_.getReclaimnum());
                    list.add(reward);
                    String title = GameString.活动结束自动回收_title().getText();
                    String content = GameString.活动结束自动回收_msg("天公将军", "" + currency.getNumber(), "" + item_.getName(), "" + currency.getNumber() * item_.getReclaimnum()).getText();
                    new MailHandle().sendMail(getPlayerCode(), MailTypeEnum.Mail, title, content, CCReason.心仪武将活动抽奖道具清空, list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
            return;
        }

        // 区活动开启，但自己没开启，重置活动
        if (sai.running() && !running()) {
            setTimeline(sai.getTimeline());
            //重置任务和商品和活动武将等信息
            reset();
            set();
        }

        //更新任务状态
        DateTime now = DateTime.now();
        int days = ActiveUtil.days(getUpdate(), now);
        if (days >= 1) {        //转天更新

            DateTime startTime = sai.getTimeline().getStartTime();
            int activityHasPassTime = ActiveUtil.days(startTime, now) + 1;
            setDay(activityHasPassTime);
            setUpdate(now);
            set();
            TaskHandle.handle(getPlayerCode(), TaskType.指标型_心仪武将登录天数_达到, activityHasPassTime);
        }

    }

    //重置
    private void reset() {
        //商品表
        Map<String, actfavoritewarlordshop> shopMap = ActDataCenter.getAllData(actfavoritewarlordshop.class, getPlayerCode());

        //任务表
        Map<String, actfavoritewarlordreward> taskMap = ActDataCenter.getAllData(actfavoritewarlordreward.class, getPlayerCode());

        //重置商品
        resetGiftPackage(shopMap);

        //重置任务
        resetTask(taskMap);

        //设置活动的武将id
        setSelectid(0);

        //阵容重置
        setFormat(null);

        //已发过奖励的关卡重置
        setRewardList(new ArrayList<String>());

        //抽卡次数重置
        setCknum(0);

        //设置时间
        setDay(1);
        setUpdate(DateTime.now());

        //进度重置
        setProcess(1);

        TaskHandle.handle(getPlayerCode(), TaskType.指标型_心仪武将登录天数_达到, 1);
    }

    //重置商品
    private void resetGiftPackage(Map<String, actfavoritewarlordshop> agrmap) {
        //商城
        setDgifts(new ArrayList<FavouritePackage>());
        for (actfavoritewarlordshop data : agrmap.values()) {
            FavouritePackage dgift = new FavouritePackage();
            dgift.setId(data.getId());
            dgift.setGoodsid(data.getChargeid());
            dgift.setNumlimit(data.getLimit());//限购次数
            dgift.setType(data.getType());//类型
            dgift.setBuyNum(0); //已购买次数；
            getDgifts().add(dgift);
        }

    }

    //重置任务
    private void resetTask(Map<String, actfavoritewarlordreward> agrmap) {

        //清除任务
        for (FavouriteTask gt : getTaskMap().values()) {
            Task.remove(getPlayerCode(), gt.getFreeTaskCode());
            Task.remove(getPlayerCode(), gt.getPreTaskCode());
        }

        //重置任务  付费和不免费任务
        setTaskMap(new HashMap<Integer, FavouriteTask>());
        for (actfavoritewarlordreward data : agrmap.values()) {
            FavouriteTask favouriteTask = new FavouriteTask();
            favouriteTask.setId(data.getId());
            favouriteTask.setSort(data.getSort());
            favouriteTask.setType(data.getType());
            favouriteTask.setFreeTaskId(data.getTaskid());
            favouriteTask.setPreTaskId(data.getPretaskid());

            task freeTask = DataCenter.getData(data.getTaskid(), task.class);
            if (freeTask == null) {
                continue;
            }

            task preTask = DataCenter.getData(data.getPretaskid(), task.class);
            if (preTask == null) {
                continue;
            }

            Task freeTaskBean = Task.create(getPlayerCode(), freeTask);
            Task pretaskbean = Task.create(getPlayerCode(), preTask);
            favouriteTask.setFreeTaskCode(freeTaskBean.getCode());
            favouriteTask.setPreTaskCode(pretaskbean.getCode());
            getTaskMap().put(data.getId(), favouriteTask);
        }

    }

    /**
     * 解锁单 加 设置购买时间
     *
     * @param goodsid
     * @param buytime
     */
    public void unlockGiftPackageAndSetBuyTime(String pcode, int goodsid, DateTime buytime) {
        for (FavouritePackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                int buyNum = dgift.getBuyNum();
                buyNum++;
                dgift.setBuyNum(buyNum); //修改已购买数量

                //如果是卡包，任务处理
                if (dgift.getId() == 8) {
                    TaskHandle.handle(pcode, TaskType.指标型_心仪武将卡包购买_达到, 1);
                }
                set();
            }


        }
    }

    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_武将直升活动
     *
     * @param playerCode
     * @return
     */
    public static ActiveModule_心仪武将活动 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_心仪武将活动 module = getv(key(playerCode));
            if (module == null) {

                //新用户不需要去查数据库
                if (!isNewPlayer) {
                    module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_心仪武将活动.class);
                    if (module != null) {
                        module.set();
                    }//同步到redis
                }

                if (module == null) {
                    module = create(playerCode);
                }
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        if (running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

        if (running()) {
            checkReward();               //检查奖励是否领取
            checkGachaHero();            //检查是否能抽奖
        } else {
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_心仪武将, false);
        }
    }

    private void checkGachaHero() {
        try {
            //检查是否可消费
            actfavoritewarlord rewardData = DataCenter.getData(1, actfavoritewarlord.class);
            Currency item = Item.get(getPlayerCode(), CurrencyType.CT_物品, rewardData.getCostid());
            if (item.getNumber() > 0) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_心仪武将招募, true);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        new TipHandle().updateTip(getPlayerCode(), TipType.活动_心仪武将招募, false);
    }

    private void checkReward() {
        for (FavouriteTask favouriteTask : getTaskMap().values()) {
            Task taskbean = Task.get(getPlayerCode(), favouriteTask.getFreeTaskCode());
            int canget = taskbean.isReward() ? DrawStatus.hadget.getStatus() : taskbean.isFinish() ? DrawStatus.canget.getStatus() : DrawStatus.cannotget.getStatus();
            if (canget == 1) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_心仪武将奖励, true);
                return;
            }
        }
        new TipHandle().updateTip(getPlayerCode(), TipType.活动_心仪武将奖励, false);
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_心仪武将活动 activeModule_心仪武将活动 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_心仪武将活动);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

}
